import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;

public class ChatServer{
  Vector<String> users = new Vector<String>();
  Vector<HandleClient> clients = new Vector<HandleClient>();

  int PORT = 56332;
  int NumClients = 10;

  public void process() throws Exception{
      ServerSocket server = new ServerSocket(PORT,NumClients);
      out.println("Savienojums ar KNAB izveidots...");
      while(true){
         Socket client = server.accept();
         HandleClient c = new HandleClient(client);
         clients.add(c);
      }  // end of while
  }

  public static void main(String ... args) throws Exception{
      new ChatServer().process();
  } // end of main

  public void boradcast(String user, String message){
        // send message to all connected users
        for (HandleClient c : clients)
           if (!c.getUserName().equals(user)){
              c.sendMessage(user,message);
           }
  }

  class HandleClient extends Thread{
    String name = "";
    BufferedReader input;
    PrintWriter output;

    public HandleClient(Socket client) throws Exception{
          // get input and output streams
         input = new BufferedReader(new InputStreamReader(client.getInputStream())) ;
         output = new PrintWriter (client.getOutputStream(),true);
         output.println("!\n");
         // read name
         output.println("Ievadi savu sevis saukli: ");
         name  = input.readLine();
         users.add(name); // add to vector
         output.println(name + ", no šī brīža esi uzskaitē. Nekusties!");
         start();
    }

    public void sendMessage(String uname,String  msg){
        output.println( uname + ":" + msg);
    }

    public String getUserName(){  
        return name; 
    }

    public void run(){
         String line;
         try{
            while(true){
            	output.println("Tu saki: ");
            	line = input.readLine();
                if("EOF".equals(line)){
                	output.println("Savienojums tiek pārtraukts . . .");
                	clients.remove(this);
                	users.remove(name);
                	break;
                }
                else if(name.equals(line)){
                	output.println("OK");
                }
                output.println("\n" + name + " saka: " + line);
                boradcast(name,line); // method  of outer class - send messages to all
            }// end of while
         } // try
         catch(Exception e) 
         {
           System.out.println(e.getMessage());
         }
    } // end of run()
  } // end of inner class
} // end of Server